//
//  HMPictureSelectorController.swift
//  01-SinaWeibo
//
//  Created by 周英培 on 16/5/29.
//  Copyright © 2016年 周英培. All rights reserved.
//

import UIKit
import SnapKit
import HMImagePicker
private let reuseIdentifier = "Cell"

private let pictMargin : CGFloat = 3
private let pictureCount : CGFloat = 4
private let imageMaxCount = 4 //设置最多添加的图片数量
private let pictureWidth : CGFloat = (ScreenWidth - (pictureCount + 1) * pictMargin) / pictureCount

class HMPictureSelectorController: UICollectionViewController {
    
    //声明数组  使用第三方框架实现多张照片上传用到的
    lazy var selectedAssets : [PHAsset] = [PHAsset]()
    
    //定义图片存储数组  不定义成私有的 发布微博界面可以调用
    lazy var images : [UIImage] = [UIImage]()

    init() {
        let flowLayout = UICollectionViewFlowLayout()
        
        flowLayout.itemSize = CGSize(width:pictureWidth , height: pictureWidth)
        
        flowLayout.minimumLineSpacing = pictMargin
        flowLayout.minimumInteritemSpacing = pictMargin
        
        flowLayout.sectionInset = UIEdgeInsetsMake(pictMargin, pictMargin, 0, pictMargin)
        
        super.init(collectionViewLayout:flowLayout)
        
        //设置背景颜色 取消图片选择器的view的黑色背景  是self.collectionView  不是self.view
        self.collectionView?.backgroundColor = UIColor.whiteColor()
    
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        //注册cell
        self.collectionView!.registerClass(HMPictureSelectorCell.self, forCellWithReuseIdentifier: reuseIdentifier)

    }

    
    // MARK: UICollectionViewDataSource

    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        //加一 是因为 初次时 是没有图片的 是空的
        let delt = images.count == imageMaxCount ? 0 : 1 //用来判断 然后实现最多添加四张图片的效果
        return images.count + delt
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! HMPictureSelectorCell
    
        cell.backgroundColor = randomColor()
        
        //需要判断 因为images.count + 1 跟cell的索引起冲突
        if indexPath.item == images.count {
            
            cell.image = nil
            
        } else {
        
            cell.image = images[indexPath.item]
        
        }
        
        //设置代理
        cell.selectordelegate = self
    
        return cell
    }
  
}

//遵守图片选择器的协议 需要遵守两个协议  实现的添加上传单张图片
extension HMPictureSelectorController : UIImagePickerControllerDelegate,UINavigationControllerDelegate{

   
    //实现协议方法
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        
        //保存图片
        images.append(image)
        
        self.collectionView?.reloadData()
        
       //实现协议方法之后，程序员控制视图控制器的dismiss
        dismissViewControllerAnimated(true) { 
            
            //刷新 放在里面 刷新图片太慢 不符合需求 放在外面
//            self.collectionView?.reloadData()
        }
        
    }

}

//第三方框架实现添加上传多张图片的OC方法  遵守协议
extension HMPictureSelectorController : HMImagePickerControllerDelegate {

    func imagePickerController(picker: HMImagePickerController, didFinishSelectedImages images: [UIImage], selectedAssets: [PHAsset]?) {
        //记录图像，方便在 CollectionView 显示
        self.images = images
        // 记录选中资源集合，方便再次选择照片定位  意思就是 你选中什么照片 再返回的时候 能够知道上次选的啥图片
        self.selectedAssets = selectedAssets!
        //刷新
        collectionView?.reloadData()
        dismissViewControllerAnimated(true, completion: nil)
        
        // 记录图像，方便在 CollectionView 显示
        //        self.images = images;
        //        // 记录选中资源集合，方便再次选择照片定位
        //        self.selectedAssets = selectedAssets;
        //
        //        [self.collectionView reloadData];
        //
        //        [self dismissViewControllerAnimated:YES completion:nil];
    }

}

//使用分类继承的方式 遵守协议(系统的是每次添加上传一张图片) 用第三方框架 实现添加上传多张图片
extension HMPictureSelectorController : HMPictureSelectorCellDelegate {

    //实现协议方法
    func willAddPicture() {
        print("图片添加")
        //苹果系统自带的相册选择器
        //首先判断用户是否有访问相册权限
        if !UIImagePickerController.isSourceTypeAvailable(.SavedPhotosAlbum) {
            
            print("抱歉没有访问权限")
            
        }
        
        //第三方框架实现添加上传多张图片的方法
        let picker = HMImagePickerController(selectedAssets: selectedAssets)
        //设置图像选择代理   这个代理不要写错了 不要写成了picker.delegate = self  坑死人

        picker.pickerDelegate = self
        //设置目标图片尺寸
        picker.targetSize = CGSizeMake(600, 600)
        //设置最大选择照片数量
        picker.maxPickerCount = imageMaxCount
        
        presentViewController(picker, animated: true, completion: nil)
        
        
        /*  第三方框架实现添加上传多张图片的OC方法
         HMImagePickerController *picker = [[HMImagePickerController alloc] initWithSelectedAssets:self.selectedAssets];
         
         // 设置图像选择代理
         picker.pickerDelegate = self;
         // 设置目标图片尺寸
         picker.targetSize = CGSizeMake(600, 600);
         // 设置最大选择照片数量
         picker.maxPickerCount = 9;
         
         [self presentViewController:picker animated:YES completion:nil];
         */
        
        //系统的添加上传一张图片
//        let picker = UIImagePickerController()
//        
//        //给图片选择器设置代理
//        picker.delegate = self
//        
//        //设置图片可以编辑 即可以对图片进行修改
////        picker.allowsEditing = true
//        
//        self.presentViewController(picker, animated: true, completion: nil)
        
    }
    
    func willDeletePicture(cell: HMPictureSelectorCell) {
        
        print("图片删除")
        
        //获取对应的cell 的indexPath
        guard  let indexPath = collectionView?.indexPathForCell(cell) else {
            
            return
        
        }
        
        //删除对应的item
        images.removeAtIndex(indexPath.item)
        
        //删除记录选中资源集合中的元素  意思就是能够知道上次删除的图片
        selectedAssets.removeAtIndex(indexPath.item)
        
        //删除完之后进行刷新
        self.collectionView?.reloadData()
        
        
    }
    
    


}

//MARK:定义协议 
@objc protocol HMPictureSelectorCellDelegate : NSObjectProtocol {
 
    //定义协议方法 可选的
    optional func willAddPicture()
    
    //里面加上这个参数 是为了 把对应的cell给传递过去
    optional func willDeletePicture(cell:HMPictureSelectorCell)

}


class HMPictureSelectorCell: UICollectionViewCell {
    
    //定义图片属性 给cell赋值图片
    var image : UIImage? {
    
        didSet {
        
            //让没有图片的添加按钮的上面的删除按钮隐藏 下面必须得隐藏 因为一 初次运行时会崩溃 二 到最后删除最后一张时 会崩溃
            deleteBtn.hidden = image == nil
            addBtn.setImage(image, forState: .Normal)
        
        }
    
    }
    
    
    //定义代理属性 要用 weak修饰 弱引用 解决循环引用
    weak var selectordelegate : HMPictureSelectorCellDelegate?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setUpUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //MARK:设置UI
    private func setUpUI() {
        contentView.addSubview(addBtn)
        contentView.addSubview(deleteBtn)
        
        //设置约束
        addBtn.snp_makeConstraints { (make) in
            make.edges.equalTo(contentView)
        }
        deleteBtn.snp_makeConstraints { (make) in
            make.top.right.equalTo(contentView)
        }
        
        //添加按钮和删除按钮的点击事件
        addBtn.addTarget(self, action: #selector(addBtnClick), forControlEvents: .TouchUpInside)
        deleteBtn.addTarget(self, action: #selector(deleteBtnClick), forControlEvents: .TouchUpInside)
    }
    
    //MARK:懒加载各个子控件
    //添加照片按钮
    private lazy var addBtn : UIButton = {
        
        let btn = UIButton()
        
        //设置背景图片
        btn.setBackgroundImage(UIImage(named:"compose_pic_add"), forState:.Normal)
        
        //裁剪  btn里面又一个imageview  裁剪 要对按钮的imageview进行裁剪
        btn.imageView?.contentMode = .ScaleAspectFill
        btn.imageView?.clipsToBounds = true
        
        
        return btn
    }()
    
    //删除按钮
    private lazy var deleteBtn : UIButton = {
        
        let btn = UIButton()
        
        //设置背景图片
        btn.setImage(UIImage(named:"compose_photo_close"), forState: .Normal)
        
        return btn
        
    }()
    
    
    
    //MARK:按钮的响应点击事件
    @objc private func addBtnClick() {
        
        print("添加照片")
        
        //添加按钮上添加图片后不能再被点击添加
        if image != nil {
            
            return
            
        }
        
        //调用协议方法
        selectordelegate?.willAddPicture?()
        
    }
    
    @objc private func deleteBtnClick() {
        
        print("删除图片")
        
        //self 把点击的cell传递过去
        selectordelegate?.willDeletePicture?(self)
        
    }
    
}


extension HMPictureSelectorController {

    // MARK: UICollectionViewDelegate
    
    /*
     // Uncomment this method to specify if the specified item should be highlighted during tracking
     override func collectionView(collectionView: UICollectionView, shouldHighlightItemAtIndexPath indexPath: NSIndexPath) -> Bool {
     return true
     }
     */
    
    /*
     // Uncomment this method to specify if the specified item should be selected
     override func collectionView(collectionView: UICollectionView, shouldSelectItemAtIndexPath indexPath: NSIndexPath) -> Bool {
     return true
     }
     */
    
    /*
     // Uncomment these methods to specify if an action menu should be displayed for the specified item, and react to actions performed on the item
     override func collectionView(collectionView: UICollectionView, shouldShowMenuForItemAtIndexPath indexPath: NSIndexPath) -> Bool {
     return false
     }
     
     override func collectionView(collectionView: UICollectionView, canPerformAction action: Selector, forItemAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) -> Bool {
     return false
     }
     
     override func collectionView(collectionView: UICollectionView, performAction action: Selector, forItemAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) {
     
     }
     */
    
}
